package com.train.webadmin.app.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.*;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.train.webadmin.app.service.*;
import com.train.webadmin.app.dao.*;
import com.train.webadmin.app.model.*;
import com.train.common.core.base.dao.BaseDaoMapper;
import com.train.common.core.constant.GlobalDeletedFlag;
import com.train.common.core.object.Tuple2;
import com.train.common.core.object.TokenData;
import com.train.common.core.object.MyRelationParam;
import com.train.common.core.object.CallResult;
import com.train.common.core.base.service.BaseService;
import com.train.common.core.util.MyModelUtil;
import com.github.pagehelper.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 试卷题目数据操作服务类。
 *
 * @author xulei
 * @date 2025-03-07
 */
@Slf4j
@Service("tQuestionInfoService")
public class TQuestionInfoServiceImpl extends BaseService<TQuestionInfo, Long> implements TQuestionInfoService {

    @Autowired
    private TQuestionInfoMapper tQuestionInfoMapper;
    @Autowired
    private TPaperQuestMapper tPaperQuestMapper;
    @Autowired
    private CourseInfoService courseInfoService;
    @Autowired
    private TPaperInfoService tPaperInfoService;

    /**
     * 返回当前Service的主表Mapper对象。
     *
     * @return 主表Mapper对象。
     */
    @Override
    protected BaseDaoMapper<TQuestionInfo> mapper() {
        return tQuestionInfoMapper;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public TQuestionInfo saveNew(TQuestionInfo tQuestionInfo) {
        tQuestionInfoMapper.insert(this.buildDefaultValue(tQuestionInfo));
        return tQuestionInfo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveNewBatch(List<TQuestionInfo> tQuestionInfoList) {
        if (CollUtil.isNotEmpty(tQuestionInfoList)) {
            tQuestionInfoList.forEach(this::buildDefaultValue);
            tQuestionInfoMapper.insertList(tQuestionInfoList);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveNewOrUpdateBatch(List<TQuestionInfo> tQuestionInfoList, List<String> duplicateVerifyColumns, int batchSize) {
        if (CollUtil.isEmpty(tQuestionInfoList)) {
            return;
        }
        if (batchSize <= 0) {
            batchSize = CollUtil.isNotEmpty(duplicateVerifyColumns) ? 100 : 10000;
        }
        int start = 0;
        do {
            int end = Math.min(tQuestionInfoList.size(), start + batchSize);
            List<TQuestionInfo> subList = tQuestionInfoList.subList(start, end);
            if (CollUtil.isNotEmpty(duplicateVerifyColumns)) {
                Tuple2<List<TQuestionInfo>, List<TQuestionInfo>> t = this.deduceInsertOrUpdateList(subList, duplicateVerifyColumns);
                if (CollUtil.isNotEmpty(t.getFirst())) {
                    t.getFirst().forEach(this::buildDefaultValue);
                    tQuestionInfoMapper.insertList(t.getFirst());
                }
                t.getSecond().forEach(data -> tQuestionInfoMapper.updateById(data));
            } else {
                tQuestionInfoList.forEach(this::buildDefaultValue);
                tQuestionInfoMapper.insertList(subList);
            }
            if (end == tQuestionInfoList.size()) {
                break;
            }
            start += batchSize;
        } while (true);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean update(TQuestionInfo tQuestionInfo, TQuestionInfo originalTQuestionInfo) {
        tQuestionInfo.setCreateUserId(originalTQuestionInfo.getCreateUserId());
        tQuestionInfo.setUpdateUserId(TokenData.takeFromRequest().getUserId());
        tQuestionInfo.setCreateTime(originalTQuestionInfo.getCreateTime());
        tQuestionInfo.setUpdateTime(new Date());
        // 这里重点提示，在执行主表数据更新之前，如果有哪些字段不支持修改操作，请用原有数据对象字段替换当前数据字段。
        UpdateWrapper<TQuestionInfo> uw = this.createUpdateQueryForNullValue(tQuestionInfo, tQuestionInfo.getId());
        return tQuestionInfoMapper.update(tQuestionInfo, uw) == 1;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean remove(Long id) {
        if (tQuestionInfoMapper.deleteById(id) == 0) {
            return false;
        }
        // 开始删除多对多子表的关联
        TPaperQuest tPaperQuest = new TPaperQuest();
        tPaperQuest.setQuestionId(id);
        tPaperQuestMapper.delete(new QueryWrapper<>(tPaperQuest));
        return true;
    }

    @Override
    public List<TQuestionInfo> getTQuestionInfoList(TQuestionInfo filter, String orderBy) {
        return tQuestionInfoMapper.getTQuestionInfoList(filter, orderBy);
    }

    @Override
    public List<TQuestionInfo> getTQuestionInfoListWithRelation(TQuestionInfo filter, String orderBy) {
        List<TQuestionInfo> resultList = tQuestionInfoMapper.getTQuestionInfoList(filter, orderBy);
        // 在缺省生成的代码中，如果查询结果resultList不是Page对象，说明没有分页，那么就很可能是数据导出接口调用了当前方法。
        // 为了避免一次性的大量数据关联，规避因此而造成的系统运行性能冲击，这里手动进行了分批次读取，开发者可按需修改该值。
        int batchSize = resultList instanceof Page ? 0 : 1000;
        this.buildRelationForDataList(resultList, MyRelationParam.normal(), batchSize);
        return resultList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addTPaperQuestList(List<TPaperQuest> tPaperQuestList, Long questionId) {
        TokenData tokenData = TokenData.takeFromRequest();
        for (TPaperQuest tPaperQuest : tPaperQuestList) {
            tPaperQuest.setQuestionId(questionId);
            tPaperQuest.setCreateTime(new Date());
            tPaperQuest.setUpdateTime(new Date());
            tPaperQuest.setCreateUserId(tokenData.getUserId());
            tPaperQuest.setUpdateUserId(tokenData.getUserId());
            tPaperQuestMapper.insert(tPaperQuest);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateTPaperQuest(TPaperQuest tPaperQuest) {
        TPaperQuest filter = new TPaperQuest();
        filter.setQuestionId(tPaperQuest.getQuestionId());
        filter.setPaperId(tPaperQuest.getPaperId());
        TPaperQuest originalOne = tPaperQuestMapper.selectOne(new QueryWrapper<>(filter));
        tPaperQuest.setCreateTime(originalOne.getCreateTime());
        tPaperQuest.setUpdateTime(new Date());
        tPaperQuest.setCreateUserId(originalOne.getCreateUserId());
        tPaperQuest.setUpdateUserId(TokenData.takeFromRequest().getUserId());
        UpdateWrapper<TPaperQuest> uw =
                BaseService.createUpdateQueryForNullValue(tPaperQuest, TPaperQuest.class);
        uw.setEntity(filter);
        return tPaperQuestMapper.update(tPaperQuest, uw) > 0;
    }

    @Override
    public TPaperQuest getTPaperQuest(Long questionId, Long paperId) {
        TPaperQuest filter = new TPaperQuest();
        filter.setQuestionId(questionId);
        filter.setPaperId(paperId);
        return tPaperQuestMapper.selectOne(new QueryWrapper<>(filter));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removeTPaperQuest(Long questionId, Long paperId) {
        TPaperQuest filter = new TPaperQuest();
        filter.setQuestionId(questionId);
        filter.setPaperId(paperId);
        return tPaperQuestMapper.delete(new QueryWrapper<>(filter)) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeTPaperQuestList(Long questionId, List<Long> paperIdList) {
        LambdaQueryWrapper<TPaperQuest> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TPaperQuest::getQuestionId, questionId);
        queryWrapper.in(TPaperQuest::getPaperId, paperIdList);
        tPaperQuestMapper.delete(queryWrapper);
    }

    @Override
    public CallResult verifyImportList(List<TQuestionInfo> dataList, Set<String> ignoreFieldSet) {
        CallResult callResult;
        if (!CollUtil.contains(ignoreFieldSet, "courseId")) {
            callResult = verifyImportForDatasourceDict(dataList, "courseIdDictMap", TQuestionInfo::getCourseId);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        if (!CollUtil.contains(ignoreFieldSet, "paperId")) {
            callResult = verifyImportForDatasourceDict(dataList, "paperIdDictMap", TQuestionInfo::getPaperId);
            if (!callResult.isSuccess()) {
                return callResult;
            }
        }
        return CallResult.ok();
    }

    @Override
    public CallResult verifyRelatedData(TQuestionInfo tQuestionInfo, TQuestionInfo originalTQuestionInfo) {
        String errorMessageFormat = "数据验证失败，关联的%s并不存在，请刷新后重试！";
        //这里是基于字典的验证。
        if (this.needToVerify(tQuestionInfo, originalTQuestionInfo, TQuestionInfo::getCourseId)
                && !courseInfoService.existId(tQuestionInfo.getCourseId())) {
            return CallResult.error(String.format(errorMessageFormat, "课程id"));
        }
        //这里是基于字典的验证。
        if (this.needToVerify(tQuestionInfo, originalTQuestionInfo, TQuestionInfo::getPaperId)
                && !tPaperInfoService.existId(tQuestionInfo.getPaperId())) {
            return CallResult.error(String.format(errorMessageFormat, "试卷id"));
        }
        return CallResult.ok();
    }

    private TQuestionInfo buildDefaultValue(TQuestionInfo tQuestionInfo) {
        TokenData tokenData = TokenData.takeFromRequest();
        tQuestionInfo.setCreateUserId(tokenData.getUserId());
        tQuestionInfo.setUpdateUserId(tokenData.getUserId());
        Date now = new Date();
        tQuestionInfo.setCreateTime(now);
        tQuestionInfo.setUpdateTime(now);
        tQuestionInfo.setDeletedFlag(GlobalDeletedFlag.NORMAL);
        MyModelUtil.setDefaultValue(tQuestionInfo, "correctAnswer", "");
        MyModelUtil.setDefaultValue(tQuestionInfo, "options", "");
        return tQuestionInfo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<TQuestionInfo> getQuestionInfoByPaperId(Long paperId) {
        return tQuestionInfoMapper.getQuestionInfoByPaperId(paperId);
    }
}
